/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.coinche.server;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Singleton;

/*
 * Ajout d'entete de mis en cache pour les données 
 */
@Singleton
public class CacheFilter implements Filter {

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {}
	
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {}

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(	ServletRequest request, 
							ServletResponse response,
							FilterChain filterChain) throws IOException, ServletException {

 		HttpServletRequest httpRequest = (HttpServletRequest)request;

 		String requestURI = httpRequest.getRequestURI();
 		if( !requestURI.contains(".nocache.") && !requestURI.endsWith("/rpc")){
 			long today = new Date().getTime();
 			HttpServletResponse httpResponse = (HttpServletResponse)response;
 			
 			if (requestURI.contains(".cache.")) {
 				/*
 				 * Un an
 				 */
 				httpResponse.setDateHeader("Expires", today+31536000000L);
 				httpResponse.setHeader("Cache-Control", "max-age=" + Long.toString(31536000L) + ", public");
 			} else {
 				/*
 				 * Une semaine
 				 */
 				httpResponse.setDateHeader("Expires", today+604800000L);
 				httpResponse.setHeader("Cache-Control", "max-age=" + Long.toString(604800L) + ", public");
 			}
 		}
 		filterChain.doFilter(request, response);
 	}
}
